package org.oexam.ostudy.serv;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.oexam.ostudy.db.DBConnection;
import org.oexam.ostudy.db.TestAccess;
import org.oexam.ostudy.facade.struct.LoggedUserDetails;
import org.oexam.ostudy.facade.struct.TestNameAndId;
import org.oexam.ostudy.misc.GeneralConstants;
import org.oexam.ostudy.struct.AllResults;

/**
 * Servlet implementation class ViewResultsOfTest
 */
@WebServlet("/ViewResultsOfTest")
public class ViewResultsOfTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewResultsOfTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LoggedUserDetails details = (LoggedUserDetails) request.getSession()
				.getAttribute("userLoginDetails");

		if (details == null) {
			response.sendRedirect("Login.jsp");
		}
		if (details.isAuthenticated() && (details.getUserType() == 1)) {

			
			DBConnection dbConnection = new DBConnection();

			ResultSet rs = null;
			try {
				rs = dbConnection
						.executeQuery(GeneralConstants.select_all_sql + "AllResults"
								+ " where test_id=" + request.getParameter("TID"));
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			List<AllResults> listOfresults = new ArrayList<AllResults>();
			try {
				while (rs.next()) {
					AllResults allResults = new AllResults();
					allResults.setStudent_id(rs.getInt("student_id"));
					allResults.setResult(rs.getInt("Result"));
					listOfresults.add(allResults);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		    request.getSession().setAttribute("listOfresults", listOfresults);
			response.sendRedirect("ViewResultsOfATest.jsp");

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
